package org.ghost.spring.cloud.config.client.demo.common.json.deserialize;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.google.common.collect.Lists;
import org.ghost.spring.cloud.config.client.demo.util.DateUtil;

import java.io.IOException;
import java.util.Date;
import java.util.List;

public class StringArray2DateArrayDeserializer extends JsonDeserializer<Date[]> {
    @Override
    public Date[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonToken currentToken = p.getCurrentToken();
        if (currentToken == JsonToken.START_ARRAY) {
            List<String> dates = Lists.newArrayList();
            while (p.nextTextValue() != null) {
                String data = p.getText();
                if (data != null && data.length() > 0) {
                    dates.add(data);
                }
            }
            if (dates.size() > 0) {
                Date[] result = new Date[dates.size()];
                for (int i = 0; i < dates.size(); i++) {
                    result[i] = DateUtil.strToDateYMD_HMS(dates.get(i));
                }
                return result;
            }
        }

        return null;
    }
}